//
//  ColorWheelView.swift
//  Example
//
//  Created by xx on 2025/3/24.
//
import UIKit
import FastSwiftSDK

class ColorWheelView: UIView {
    
    var callBack:FastStrBlock?
    
    // 当前选中的颜色
    var selectedColor: UIColor = .white {
        didSet {
            self.backgroundColor = selectedColor
            self.callBack?(selectedColor.hexString)
        }
    }

    // 重写绘制方法
    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else { return }

        // 获取视图中心点和半径
        let center = CGPoint(x: rect.midX, y: rect.midY)
        let radius = min(rect.width, rect.height) / 2 - 10

        // 绘制色环
        for hue in stride(from: 0.0, to: 1.0, by: 0.01) {
            let color = UIColor(hue: hue, saturation: 1.0, brightness: 1.0, alpha: 1.0)
            color.setFill()

            let startAngle = CGFloat(hue) * 2 * .pi
            let endAngle = CGFloat(hue + 0.01) * 2 * .pi

            let path = UIBezierPath()
            path.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
            path.addLine(to: center)
            path.close()

            path.fill()
        }
    }

    // 处理触摸事件
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            guard let touch = touches.first else { return }

            // 获取触摸点的位置
            let location = touch.location(in: self)

            // 获取视图中心点
            let center = CGPoint(x: bounds.midX, y: bounds.midY)

            // 计算触摸点相对于中心的距离和角度
            let dx = location.x - center.x
            let dy = location.y - center.y
            let distance = sqrt(dx * dx + dy * dy)
            let angle = atan2(dy, dx)

            // 打印调试信息
            print("Touch Location: \(location)")
            print("Delta X: \(dx), Delta Y: \(dy)")
            print("Calculated Angle (radians): \(angle)")

            // 确保点击在色环范围内
            let radius = min(bounds.width, bounds.height) / 2 - 10
            if distance <= radius {
                // 根据角度计算色调 (hue)
                var hue = (angle) / (2 * .pi) // 将 [-π, π] 映射到 [0, 1]
                if hue < 0 { hue += 1.0 }
                if hue > 1 { hue -= 1.0 }

                // 打印色调值
                print("Calculated Hue: \(hue)")

                // 设置选中的颜色 (饱和度和亮度固定为1.0)
                selectedColor = UIColor(hue: CGFloat(hue), saturation: 1.0, brightness: 1.0, alpha: 1.0)

                // 刷新视图以更新选中状态
                setNeedsDisplay()
            } else {
                print("Touch outside the color wheel.")
            }
        }
}

// 扩展 UIColor，添加生成 16 进制字符串的功能
extension UIColor {
    var hexString: String {
        var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
        getRed(&r, green: &g, blue: &b, alpha: &a)
        let rgb: Int = (Int)(r * 255) << 16 | (Int)(g * 255) << 8 | (Int)(b * 255)
        return String(format: "#%06x", rgb)
    }
}
